//
//  ConsultaionCommentTableViewCell.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/2.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import TYAttributedLabel
import Alamofire
import SwiftyJSON
import PKHUD

protocol ConsultaionCommentTableViewCellDelegate: NSObjectProtocol {
    func reloadSuperTable(_ cell: ConsultaionCommentTableViewCell)
    func like(model:myCommendModel,tag:Int)
    func moreAct(model: myCommendModel) -> Void
    func jb(model: myCommendModel, reportType:String) -> Void
}

class ConsultaionCommentTableViewCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var likeImageView: UIImageView!
    @IBOutlet weak var commentCountLabel: UILabel!
    
    @IBOutlet weak var headerImageView: BaseCircleImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var levelLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var contentLabel: TYAttributedLabel!
    @IBOutlet weak var contentLabelhegiht: NSLayoutConstraint!
    @IBOutlet weak var subReplyTableView: UITableView!
    @IBOutlet weak var moreButton: UIButton!
    @IBOutlet weak var subReplyTableViewHeight: NSLayoutConstraint!
    @IBOutlet weak var subReplyTableViewBottomConstaint: NSLayoutConstraint!
    @IBOutlet weak var moreButtonButtomConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var bottomTableViewConstaint: NSLayoutConstraint!
    
    @IBOutlet weak var likeBtn: UIButton!
    var cellModel:myCommendModel!
    var reportType:String?
    weak var delegate: ConsultaionCommentTableViewCellDelegate?
    let TempShowLimit = 2
    let contentOffset: CGFloat = 102
    var cellHeights: [CGFloat] = []
    var replydatas: [myCommendModel] = []
    override func awakeFromNib() {
        super.awakeFromNib()
        setUI()
    }
    
    private func setUI() {
        subReplyTableView.delegate = self
        subReplyTableView.dataSource = self
        subReplyTableView.backgroundColor = UIColor.lightGray
        subReplyTableView.layer.masksToBounds = true
        subReplyTableView.layer.cornerRadius = 12
        contentLabel.textColor = ONColor.subTextColor
        contentLabel.linesSpacing = LinesSpacing
        contentLabel.font = UIFont.systemFont(ofSize: 12)
        contentLabel.layoutIfNeeded()
        
        subReplyTableView.register(UINib(nibName: "\(SubCommentTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        let long = UILongPressGestureRecognizer.init(target: self, action: #selector(handleLong(long:)))
        self.contentView.isUserInteractionEnabled = true
        self.contentView.addGestureRecognizer(long)
    }
    
    @objc func handleLong(long: UILongPressGestureRecognizer){
        
        if long.state == .began {
            self.delegate?.jb(model: self.cellModel!,reportType:self.reportType!)
        }
    }
    
    func setData(datas: myCommendModel) {
        cellModel = datas
        replydatas = datas.relatedComments
        let path:String = "\(BaseURL)\((datas.commentUser?.headIcon!)!)"
        
        
        let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
        headerImageView.sd_setImage(with: url! as URL, completed: nil)
//        levelLabel.isHidden = true
        if let constellation = datas.commentUser?.grade  {
            levelLabel.text = constellation.gradeCode
        }
        if let name = datas.commentUser?.nickname!{
            if name != "null"{
                nameLabel.text = name
            }
            else{
                nameLabel.text = ""
            }
        }

        if let time = datas.created{
            timeLabel.text = time
        }
        if let likescount = datas.likesCount{
            if likescount != "0"{
                commentCountLabel.text = likescount
            }
            else{
                commentCountLabel.text = ""
            }
        }
        if let content = datas.commentContent{
            contentLabel.text = content
        }
        if let like = datas.ifLiked{
            if like == "0"{
                likeImageView.isHighlighted = false
            }
            else{
                likeImageView.isHighlighted = true
            }
        }
        contentLabelhegiht.constant = CGFloat(contentLabel.getHeightWithWidth(ScreenWidth - contentOffset))
//        if replydatas.count > 0
//        {
//            moreButtononstaint(isMore: false)
//        }
//        else{
//            moreButtononstaint(isMore: true)
//        }
        tableHeightCalculation()
        
    }
    
    /// MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if replydatas.count > 0{
            return 1
        }
        return 0//replydatas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! SubCommentTableViewCell
        cell.backgroundColor = UIColor.clear
        cell.setData(contentOffset: contentOffset, comment: replydatas[indexPath.row], cellModel: cellModel)
        return cell
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headview = UIView()
        headview.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 10)
        headview.backgroundColor = UIColor.clear
        return headview
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footview = UIView()
        footview.frame = CGRect(x: 0, y: 0, width: ScreenWidth - contentOffset - 20, height: 35)
        footview.backgroundColor = UIColor.clear
        
        let moreBtn = UIButton(type: UIButtonType.custom)
        moreBtn.setTitle("查看更多", for: UIControlState.normal)
        moreBtn.frame = CGRect(x: footview.frame.size.width - 80, y: 0, width: 80, height: 35)
        moreBtn.contentMode = UIViewContentMode.right
        moreBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        moreBtn.setImage(UIImage.init(named: "btn_praise"), for: UIControlState.normal)
        moreBtn.setTitleColor(ONColor.subTextColor, for: UIControlState.normal)
        moreBtn.setImagePositionWith(SSImagePositionType.right, spacing: 5)
        moreBtn.addTarget(self, action: #selector(moreAct(btn:)), for: .touchUpInside)
        footview.addSubview(moreBtn)
        return footview

    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 35
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         return cellHeights[indexPath.row]
    }
    
    @objc func moreAct(btn: UIButton){
        self.delegate?.moreAct(model: cellModel)
    }
    /// MARK: - taps
    @IBAction func tapMore(_ sender: UIButton) {
        self.delegate?.reloadSuperTable(self)
    }
    @IBAction func tapLike(_ sender: UIButton) {
        guard MineInfoModel.share.hasLoginIn() else {
            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
            if let push = self.delegate as? UIViewController {
                push.navigationController?.pushViewController(loginVC, animated: true)
            }
            return
        }

        var count = 0
        if let hashText = commentCountLabel?.text?.hashValue {
            if let counts = Int(commentCountLabel.text!) {
                let countss = Int(commentCountLabel.text!)
                count = countss!
            }
        }
        
        likeImageView.isHighlighted = !likeImageView.isHighlighted
        if likeImageView.isHighlighted {
            
            commentCountLabel.text = String(count + 1)
        }else {
            if count > 1 {
                commentCountLabel.text = String(count - 1)
            }else {
                commentCountLabel.text = ""
            }
        }
        self.delegate?.like(model: cellModel,tag: sender.tag)
//        likeImageView.isHighlighted = !likeImageView.isHighlighted
    }
}

extension ConsultaionCommentTableViewCell {
    
    /// 设置回复评论的高度展示
    ///
    /// - Parameters:
    ///   - tempData: 评论数据
    ///   - isCheckAll: 是否查看全部
    func tableHeightCalculation() {
        var allHeight: CGFloat = 0
        if replydatas.count > 0 {
            let xmodel = replydatas.first
            
            
            let TBoffset: CGFloat = 5
            let view = TYAttributedLabel()
            view.frame = CGRect(x: 0, y: 0, width: ScreenWidth - contentOffset, height: 19)
            view.linesSpacing = LinesSpacing
            view.font = UIFont.systemFont(ofSize: 12)
            if let nickname = xmodel?.commentUser?.nickname!{
                view.text = nickname + "回复：" + (xmodel?.commentContent!)!
            }
            else{
                view.text = "没昵称用户回复：" + (xmodel?.commentContent!)!
            }
            //            view.text = str.commentContent!
            let height = CGFloat(view.getHeightWithWidth(view.width)) + TBoffset
            allHeight += height
            cellHeights = [height]
            allHeight += 45
        }
//
//        cellHeights = replydatas.map({ (str) -> CGFloat in
//            let TBoffset: CGFloat = 5
//            let view = TYAttributedLabel()
//            view.frame = CGRect(x: 0, y: 0, width: ScreenWidth - contentOffset, height: 19)
//            view.linesSpacing = LinesSpacing
//            view.font = UIFont.systemFont(ofSize: 12)
//            print(str.commentUser?.nickname as Any)
//            if let nickname = str.commentUser?.nickname!{
//                view.text = nickname + "回复：" + str.commentContent!
//            }
//            else{
//                view.text = "没昵称用户回复：" + str.commentContent!
//            }
////            view.text = str.commentContent!
//            let height = CGFloat(view.getHeightWithWidth(view.width)) + TBoffset
//            allHeight += height
//            return CGFloat(height)
//        })
        
        subReplyTableViewHeight.constant = allHeight
        if replydatas.count == 0 {
            bottomTableViewConstaint.constant = 0
        }
        subReplyTableView.reloadData()
    }
    
    /// 设置更多按钮
    ///
    /// - Parameter isTap: 是否点击
    func moreButtononstaint(isMore: Bool) {
        moreButton.isHidden = isMore
        moreButtonButtomConstraint.priority = isMore ? .defaultLow : .defaultHigh
        subReplyTableViewBottomConstaint.priority = isMore ? .defaultHigh : .defaultLow
    }
}
